/*
 * @描述:
 * @作者: 约訂
 * @Date: 2024-09-26 14:55:21
 * @LastEditTime: 2024-10-23 10:03:21
 * @修改人员: 约訂
 */
import { initWebSocket, sendWebSocket } from "./websocket/websocket.js";
// import { ScanStatus, WechatyBuilder, types, log } from "wechaty";
import { ScanStatus, WechatyBuilder, types, log } from "@juzi/wechaty";
import fs from "fs";
import readline from "readline";
import config from "./lib/Config.js";
import mScan from "./lib/mScan.js";
import mMessage from "./lib/mMessage.js";
import mLogin from "./lib/mLogin.js";
import mLogout from "./lib/mLogout.js";
import mWelcome from "./lib/mWelcome.js";
import { SocketTypeEnum } from "./websocket/socketTypeEnum.js";
const bot = WechatyBuilder.build(config);

// os.environ["WECHATY_PUPPET_SERVICE_AUTHORITY"] =
//   "token-service-discovery-test.juzibot.com";826649

const wsUrl = "ws://192.168.0.91:5478/ws/?bot=true";
// const wsUrl = "wss://wechaty.xigyu.com:5478/ws/?bot=true";
initWebSocket(wsUrl, bot);

const store = { qrcodeKey: "" };
const getQrcodeKey = (urlStr) => {
  const url = new URL(urlStr);
  return url.searchParams.get("key");
};

async function getVerifyCode() {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  return new Promise((resolve) => {
    rl.question("请输入验证码：", (answer) => {
      rl.close();
      resolve(answer);
    });
  });
}
bot
  .on("scan", (qrcode, status) => {
    console.log("进入扫码流程");

    if (status === types.ScanStatus.Waiting) {
      // 新二维码
      store.qrcodeKey = getQrcodeKey(qrcode) || "";
    }
    mScan(qrcode, status, sendWebSocket);
  })
  .on("verify-code", async (id, message, scene, status) => {
    /**
     * 监听验证码输入
     * scene: types.VerifyCodeScene,
     * status: types.VerifyCodeStatus
     *
     * export enum VerifyCodeStatus {
     *    UNKNOWN = 0,
     *    WAITING = 1, // 待输入
     *    EXPIRED = 2, // 过期，尚未实装，目前应该根据接口返回抛错来判断是否过期
     * }*
     *  export enum VerifyCodeScene {
     *    UNKNOWN = 0,
     *    LOGIN = 1, // 登录验证码
     *  }
     */
    console.log("进入需要验证码的流程中");
    console.log(
      `receive verify-code event, id: ${id}, message: ${message}, scene: ${types.VerifyCodeScene[scene]} status: ${types.VerifyCodeStatus[status]}`
    );
    if (
      status === types.VerifyCodeStatus.WAITING &&
      scene === types.VerifyCodeScene.LOGIN &&
      id === store.qrcodeKey
    ) {
      console.log(
        `receive verify-code event, id: ${id}, message: ${message}, scene: ${types.VerifyCodeScene[scene]} status: ${types.VerifyCodeStatus[status]}`
      );
      const verifyCode = await getVerifyCode(); // 通过一些途径输入验证码
      // let verifyCode = fs.readFileSync(conf.wxVerifyCodeFile).toString();
      // console.log(`bot.config id:${id}, verifyCode: ${verifyCode}`);
      try {
        await bot.enterVerifyCode(id, verifyCode); // 如果没抛错，则说明输入成功，会推送登录事件
        return;
      } catch (e) {
        console.log(e.message);
        // 如果抛错，请根据 message 处理，目前发现可以输错3次，超过3次错误需要重新扫码。
        // 错误关键词: 验证码错误输入错误，请重新输入
        // 错误关键词：验证码错误次数超过阈值，请重新扫码'
        // 目前不会推送 EXPIRED 事件，需要根据错误内容判断
      }
    }
  });

bot.on("login", (user) => mLogin(user, bot, sendWebSocket));
bot.on("logout", (user) => mLogout(user, sendWebSocket));
bot.on("message", (msg) => mMessage(msg, bot, sendWebSocket));
/**加入群聊触发 */
bot.on("room-join", async (room, inviteeList, inviter) => {
  console.log("加入群聊监听: ", room);
  let list = JSON.parse(JSON.stringify(await room.memberAll()));
  let listUser = [];
  let json = JSON.parse(JSON.stringify(room));

  // console.log("加入：", await room);
  // console.log("进群获取群成员");
  // console.log("群信息：", await room.sync());
  // for (let index = 0; index < 200; index++) {
  //   list[0].payload.tags = "";
  //   list[0].payload.phone = "";
  //   listUser.push(list[0].payload);
  // }
  // sendWebSocket({
  //   Type: SocketTypeEnum.allUser,
  //   Data: JSON.stringify({
  //     GroupId: json.payload.id,
  //     GroupName: json.payload.topic,
  //     MemberList: listUser,
  //   }),
  // });
  list.forEach((item, index) => {
    item.payload.tags = "";
    item.payload.phone = "";
    item.payload.AdditionalInfo = "";
    listUser.push(item.payload);
  });
  sendWebSocket({
    Type: SocketTypeEnum.allUser,
    Data: JSON.stringify({
      GroupId: json.payload.id,
      GroupName: json.payload.topic,
      MemberList: listUser,
    }),
  });
});
/**退出群聊触发 */
bot.on("room-leave", async (room, leaverList) => {
  console.log("退出群聊监听: ", room);
  let list = JSON.parse(JSON.stringify(await room.memberAll()));
  let listUser = [];
  let json = JSON.parse(JSON.stringify(room));
  // console.log(list);
  // console.log("进群获取群成员");
  // console.log("群信息：", await room.sync());
  // for (let index = 0; index < 200; index++) {
  //   list[0].payload.tags = "";
  //   list[0].payload.phone = "";
  //   listUser.push(list[0].payload);
  // }
  // sendWebSocket({
  //   Type: SocketTypeEnum.allUser,
  //   Data: JSON.stringify({
  //     GroupId: json.payload.id,
  //     GroupName: json.payload.topic,
  //     MemberList: listUser,
  //   }),
  // });
  list.forEach((item, index) => {
    item.payload.tags = "";
    item.payload.phone = "";
    item.payload.AdditionalInfo = "";
    listUser.push(item.payload);
  });
  sendWebSocket({
    Type: SocketTypeEnum.allUser,
    Data: JSON.stringify({
      GroupId: json.payload.id,
      GroupName: json.payload.topic,
      MemberList: listUser,
    }),
  });
});
/**群昵称修改回调 */
bot.on("room-topic", async (room, newTopic, oldTopic, changer) => {
  const topic = await room.topic();
  console.log(
    `Room topic changed from "${oldTopic}" to "${newTopic}" by ${changer.name()}`
  );
});
/**
 * 监听验证码输入
 * scene: types.VerifyCodeScene,
 * status: types.VerifyCodeStatus
 *
 * export enum VerifyCodeStatus {
 *    UNKNOWN = 0,
 *    WAITING = 1, // 待输入
 *    EXPIRED = 2, // 过期，尚未实装，目前应该根据接口返回抛错来判断是否过期
 * }*
 *  export enum VerifyCodeScene {
 *    UNKNOWN = 0,
 *    LOGIN = 1, // 登录验证码
 *  }
 */
// bot.on("heartbeat", (data) => {
//   // 正常展示的是 heartbeat@puppet-wechat4u:normal
//   console.log("心跳:", data);
//   sendWebSocket(
//     JSON.stringify({ type: "text", content: `机器人心跳: ${data}` })
//   );
// });
bot.on("error", (error) => {
  console.log("机器人报错码:", error.code);
  switch (error.code) {
    case 2:
      break;
    default:
      break;
  }
});
bot
  .start()
  .then(() => {
    log.info("StarterBot", "Starter Bot Started.");
  })
  .catch(async (e) => {
    console.error("Bot start() fail:", e);
    await bot.stop();
  });
console.info(mWelcome);
